<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <el-form-item label="地区名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入地区名称" maxlength="50" show-word-limit />
      </el-form-item>

      <el-form-item label="首字母" prop="initial">
        <el-input v-model="form.initial" placeholder="请输入首字母" maxlength="10" />
      </el-form-item>

      <el-form-item label="拼音" prop="pinyin">
        <el-input v-model="form.pinyin" placeholder="请输入拼音" maxlength="255" />
      </el-form-item>

      <el-form-item label="城市编码" prop="citycode">
        <el-input v-model="form.citycode" placeholder="请输入城市编码" maxlength="10" />
      </el-form-item>

      <el-form-item label="区域编码" prop="adcode">
        <el-input v-model="form.adcode" placeholder="请输入区域编码" maxlength="10" />
      </el-form-item>

      <el-form-item label="经纬度" prop="lng_lat">
        <el-input
          v-model="form.lng_lat"
          placeholder="请输入经纬度，格式：经度,纬度"
          maxlength="30"
        />
      </el-form-item>

      <el-form-item label="上级地区" v-if="parentName">
        <el-tag type="info">{{ parentName }}</el-tag>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="form.sort"
          :min="0"
          :max="9999"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ data ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { regionApi } from '@/api/system/region'

  interface AreaForm {
    id?: number
    name: string
    initial: string
    pinyin: string
    citycode: string
    adcode: string
    lng_lat: string
    parent_id: number
    sort: number
    status: number
  }

  interface Props {
    modelValue: boolean
    title: string
    data?: any
    parentId?: number
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    title: '',
    data: undefined,
    parentId: 0,
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const loading = ref(false)
  const formRef = ref()
  const form = reactive<AreaForm>({
    name: '',
    initial: '',
    pinyin: '',
    citycode: '',
    adcode: '',
    lng_lat: '',
    parent_id: 0,
    sort: 0,
    status: 1,
  })

  // 计算属性
  const visible = computed({
    get: () => props.modelValue,
    set: val => emit('update:modelValue', val),
  })

  const parentName = computed(() => {
    return props.parentId ? '子地区' : '顶级地区'
  })

  // 表单验证规则
  const rules = {
    name: [
      { required: true, message: '请输入地区名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    initial: [
      { required: true, message: '请输入首字母', trigger: 'blur' },
      { max: 10, message: '长度不能超过10个字符', trigger: 'blur' },
    ],
    pinyin: [
      { required: true, message: '请输入拼音', trigger: 'blur' },
      { max: 100, message: '长度不能超过100个字符', trigger: 'blur' },
    ],
    citycode: [{ max: 20, message: '长度不能超过20个字符', trigger: 'blur' }],
    adcode: [{ max: 20, message: '长度不能超过20个字符', trigger: 'blur' }],
    lng_lat: [{ max: 50, message: '长度不能超过50个字符', trigger: 'blur' }],
    sort: [{ type: 'number', min: 0, max: 9999, message: '排序必须在0-9999之间', trigger: 'blur' }],
  }

  // 方法
  const resetForm = () => {
    form.id = undefined
    form.name = ''
    form.initial = ''
    form.pinyin = ''
    form.citycode = ''
    form.adcode = ''
    form.lng_lat = ''
    form.parent_id = props.parentId || 0
    form.sort = 0
    form.status = 1
  }

  const initForm = () => {
    if (props.data) {
      // 编辑模式
      form.id = props.data.id
      form.name = props.data.name
      form.initial = props.data.initial || ''
      form.pinyin = props.data.pinyin || ''
      form.citycode = props.data.citycode || ''
      form.adcode = props.data.adcode || ''
      form.lng_lat = props.data.lng_lat || ''
      form.parent_id = props.data.parent_id || props.parentId || 0
      form.sort = props.data.sort || 0
      form.status = props.data.status || 1
    } else {
      // 添加模式
      resetForm()
      form.parent_id = props.parentId || 0
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true

      if (props.data?.id) {
        // 编辑模式
        const editData = {
          id: props.data.id,
          name: form.name,
          initial: form.initial,
          pinyin: form.pinyin,
          citycode: form.citycode,
          adcode: form.adcode,
          lng_lat: form.lng_lat,
          parent_id: form.parent_id,
          sort: form.sort,
          status: form.status,
        }
        await regionApi.edit(editData)
        ElMessage.success('更新成功')
      } else {
        // 新增模式
        const addData = {
          name: form.name,
          initial: form.initial,
          pinyin: form.pinyin,
          citycode: form.citycode,
          adcode: form.adcode,
          lng_lat: form.lng_lat,
          parent_id: form.parent_id,
          sort: form.sort,
          status: form.status,
        }
        await regionApi.add(addData)
        ElMessage.success('添加成功')
      }

      emit('success')
      handleClose()
    } catch (error: any) {
      if (error?.response?.data?.msg) {
        ElMessage.error(error.response.data.msg)
      } else {
        ElMessage.error('操作失败')
      }
    } finally {
      loading.value = false
    }
  }

  const handleClose = () => {
    visible.value = false
    nextTick(() => {
      formRef.value?.resetFields()
      resetForm()
    })
  }

  // 监听数据变化
  watch(() => props.data, initForm, { immediate: true })
</script>

<style scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
